package com.lujieni.netty.advanced;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.util.Scanner;

public class HelloWorldClient {
    public static void main(String[] args) throws InterruptedException {
        m1();
    }

    private static void m1() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture cf = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    ByteBuf buffer = ctx.alloc().buffer();
                                    buffer.writeBytes("fucking u\n".getBytes());
                                    ctx.writeAndFlush(buffer);


                                    buffer = ctx.alloc().buffer();
                                    buffer.writeBytes("123*******\n".getBytes());
                                    ctx.writeAndFlush(buffer);

                                    buffer = ctx.alloc().buffer();
                                    buffer.writeBytes("哈哈\n".getBytes());
                                    ctx.writeAndFlush(buffer);

                                    ctx.channel().close();
                            }
                        });
                    }
                })
                .connect(new InetSocketAddress("localhost", 8081));
        cf.channel().closeFuture().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                group.shutdownGracefully();
            }
        });
    }
}
